/**
 * @author yangjian
 */
"use strict";
jQuery(window).load(function() {

	// Page Preloader
	jQuery('#preloader').delay(100).fadeOut(function(){
		jQuery('body').delay(100);
	});
});

//全局JS对象
var __global = {

	//JDialog 的配置参数
	jdialog: {
		timer: 3000,   //提示框的显示时间
		width: 60, //对话窗口的高度，小于100表示百分比
		height : 80, //对话框高度，小于100表示百分比
		borderWidth : 8, //边框厚度
		top : 70, //对话框距离页面顶部的距离
		effect : 1,
		messageType : {
			"000" : "ok",
			"001" : "error"
		},//消息类型effect : 1 //切换过度特效， 0， 1， 2

	},

	reloadDelayTime : 1000, //页面刷新延时的时间

	jformErrorMessage : {
		empty : "请填写{cname}.",
		mobile : "请输入合法的手机号码.",
		email : "请输入合法的电子邮件地址.",
		idnum : "请输入合法的身份证号码.",
		number : "请输入有效的数字."
	},

	//列表内容的配置文档
	contentList: {
		formId: 'J_List_Form',   //列表表单ID
		checkboxName: 'ids[]',   //checkbox 的name属性，用来过滤全选的checkbox
		tableId: 'J_List_Table'         //数据类表ID
	},

	resizeLayout : function() {
		//if ( $('#right-section').height() < ($(window).height() - 95) ) {
		//
		//}
		$('#right-section').height($(window).height() - 95).css({"overflow":"auto"});
	}

};

define(function(require, exports) {

	require("icheck");
	require("jdialog");
	require("select2");
	require("switch");
	require("jform");
	require("datetimepicker");
	var template = require("jtemplate");
	template.config("openTag", "{[");
	template.config("closeTag", "]}");

	exports.init = function() {

		__global.resizeLayout();
		$(window).resize(function() {__global.resizeLayout();});

		//菜单收开事件
		$(".nav-parent > a").on('click', function(e) {

			if ( $(this).next().is(":visible") ) return;

			$(".nav-parent").find(".children").slideUp("fast");
			$(this).next().slideDown("fast");
			$(".nav-parent").find(".glyphicon-minus").addClass("glyphicon-plus").removeClass('glyphicon-minus');
			$(this).find(".pull-right").addClass("glyphicon-minus").removeClass('glyphicon-plus');
			e.stopPropagation();
		});

		//初始化菜单选择项
		$(".nav-parent").each(function(idx, ele) {

			$(ele).find(".children a").each(function(idx1, item) {
				var url = $(item).attr("href");
				if ( url == location.pathname ) {
					$(this).parent().addClass('active');
					$(ele).find(".children").show();
					return false;
				}
			});

		});

		//绑定tr和checkbox的选中事件
		//$(".table-hover tbody tr").on("click", function(e) {
		//	$(this).find(".icheck").iCheck('toggle');
		//	e.stopPropagation(); //阻止冒泡
		//});

		exports.initElements();

		//删除确认
		$(".item-remove").on("click", function(e) {
			e.stopPropagation();
			var url = $(this).attr("href");
			var __confirm = JDialog.win.work({
				title : "删除提示",
				width : 340,
				height : 180,
				borderWidth : 8,
				lock : true,
				effect : 0,
				content : '<div style="padding-top: 15px;">确定要删除该条记录吗？</div>',
				icon : 'warn',
				button : {
					'确认' : function() {
						__confirm.close();
						$.get(url, function(data) {
							exports.message({
								type : __global.jdialog.messageType[data.code],
								content : data.message,
								top: __global.jdialog.top
							});
							if ( data.code == '000' ) {
								setTimeout(function() {location.reload();}, __global.reloadDelayTime);
							}
						},"json");
					},
					'取消' : function() {
						__confirm.close();
					}
				}
			});
			return false;
		});

		//屏蔽当前active tab点击事件
		//$(".nav-tabs .active a").click(function(){
		//	return false;
		//});

		exports.managerProfile();

		//分页组件更改pagesize
		$('#per-pagesize').on('change', function() {
			var pagesize = $(this).val();
			var url = location.href;
			if ( url.indexOf('pagesize=') == -1 ) {
				var limiter = '&';
				if ( url.indexOf('?') == -1 ) {
					limiter = '?';
				}
				url += limiter+'pagesize='+pagesize;
			} else {
				url = url.replace(/pagesize=(\d+)/gmi, 'pagesize='+pagesize);
			}

			//alert(url);
			location.replace(url);
		});

		//导出数据
		$('#J_Export_btn').on('click', function() {
			//首先检查是否有选中的记录
			if ( $("#J_List_Form").find('input[name="ids[]"]:checked').length > 0 ) {
				$("#J_List_Form").append('<input type="hidden" name="__export" value="1" />').submit();
				$('input[name="__export"]').remove();
			} else {
				$("#search-form").append('<input type="hidden" name="__export" value="1" />').submit();
				$('input[name="__export"]').remove();
			}
		});
	}

	exports.initElements = function() {
		//初始化list table collspan
		$("#J_List_Table .no-records").each(function() {

			var th = $(this).parent().parent().prev().children(":first").children();
			$(this).attr('colspan', th.length);

		});

		//switch
		$(".bswitch").bootstrapSwitch({
			onColor : 'success',
			offColor : 'danger'
		});

		//icheck初始化
		$(".icheck").iCheck({
			checkboxClass: 'icheckbox_minimal-blue',
			radioClass: 'iradio_minimal-blue',
			increaseArea: '20%' // optional
		});
		//icheck全选事件
		$(".check-all").on("ifChecked", function() {
			$(this).parents("table").find('[name="'+__global.contentList.checkboxName+'"]').iCheck('check');
		}).on("ifUnchecked", function() {
			$(this).parents("table").find('[name="'+__global.contentList.checkboxName+'"]').iCheck('uncheck');
		});

		//select2
		$('.select2').select2({});

		//初始化日历控件
		$.fn.datetimepicker.dates['zh-CN'] = {
			days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
			daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
			daysMin:  ["日", "一", "二", "三", "四", "五", "六", "日"],
			months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
			monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
			today: "今天",
			suffix: [],
			meridiem: ["上午", "下午"]
		};
		$('.mdate').datetimepicker({
			language : "zh-CN",  //语言包
			format: "yyyy-mm-dd", //日期格式
			minView : "month", //最小视图，默认精确到小时
			autoclose: true,
			todayBtn: true,
			pickerPosition: "bottom-left"
		});

	}

	//通用表单验证处理
	exports.formCheckHandler = function(form_id) {
		var __form = new JForm({
			formId : form_id,
			continueCheck : false,
			showMessage : function( type, message, ele ) { //错误处理接口
				ele.focus();
				var errorElements = $(ele).parents(".form-group").next();
				if ( !errorElements.hasClass('help-block') ) {
					errorElements = $(ele).parents(".form-group").find(".help-block");
				}
				if ( type == "error" ) {
					errorElements.addClass("text-error").html(message);
				} else {
					errorElements.removeClass("text-error").empty();
				}
			}
		});

		//设置报错提示信心
		__form.setMessage(__global.jformErrorMessage);

		return __form.checkFormData();
	}

	/**
	 * 通用回调处理
	 * @param data 服务器返回数据，对象
	 * @param successCallback 操作成功时回调函数
	 * @param failCallback 操作失败时回调函数
	 */
	exports.ajaxCallback = function(data, successCallback, failCallback) {
		if ( data.code == "000" && typeof successCallback == 'function' ) {
			successCallback();
		} else if ( typeof failCallback == 'function' ) {
			failCallback();
		}

		exports.message({
			type : __global.jdialog.messageType[data.code],
			content : data.message,
			lock : true
		});

	}

	/**
	 * 表单提交通用处理函数
	 * @param formId
	 * @param url
	 * @param successCallback
	 * @param failCallback
	 * @returns {boolean}
	 */
	exports.formSubmit = function(formId, url, successCallback, failCallback) {

		if ( !exports.formCheckHandler(formId) ) return false;
		//collect form data
		var formData = $('#' + formId).serialize();
		$.post(url, formData, function (result) {
			exports.ajaxCallback(result, successCallback, failCallback);
		}, 'json');
	}

	//检测是否已存在
	exports.checkExists = function(configs) {
		$(".check-exists").on('blur', function() {
			var value = $(this).val().trim();
			if ( value == '' ) return false;
			var txt = $(this).attr('placeholder');
			var field = $(this).data('field');
			var that = this;
			$.post(configs.check_url, {
				field : field,
				value : value
			}, function(data) {
				var errorElements = $(that).parents(".form-group").next();
				if ( !errorElements.hasClass('help-block') ) {
					errorElements = $(that).parents(".form-group").find(".help-block");
				}
				if ( data.code == '000' ) {
					that.focus();
					errorElements.addClass("text-error").html(txt+'已存在');
				} else {
					errorElements.removeClass("text-error").empty();
				}
			}, 'json');
		});
	}

	//列表页面的bootswitch初始化
	exports.bswitctListInit = function(configs) {

		$('.bswitch-list').on("switchChange.bootstrapSwitch", function(event, state) {
			if ( $(this).data("cancel") ) {
				$(this).data("cancel", false);
				return false;
			}
			var id = $(this).data('id');
			var field = $(this).data('field');
			var value = state == false ? 0 : 1;
			var that = this;
			$.post(configs.set_url, {
				id : id,
				field : field,
				value : value
			}, function(data) {

				exports.message({
					type:__global.jdialog.messageType[data.code],
					top : __global.jdialog.top,
					content:data.message,
					lock:false
				});
				if ( data.code != '000' ) {
					$(that).data('cancel', true);
					if ( state == false ) {
						$(that).bootstrapSwitch('state', true);
					} else {
						$(that).bootstrapSwitch('state', false);
					}
				}

			}, 'json');
		});
	}

	//添加页面的bootswitch初始化
	exports.bswitchAddInit = function() {
		$('.bswitch-add').on("switchChange.bootstrapSwitch", function(event, state) {
			var value = state == false ? 0 : 1;
			$(this).parents('.bootstrap-switch-wrapper').next().val(value);
		});
	}

	//管理员信息编辑
	exports.managerProfile = function() {

		$("#manager-profile").on("click", function() {
			exports.post("修改管理员信息", "manager-porfile-template", {width:700, height:610}, {}, "/admin/manager/profile", "manager-porfile-form");
		});

		//修改密码
		$("#manager-pass").on("click", function() {
			exports.post("修改管理员密码", "manager-pass-template", {width:700, height:330}, {}, "/admin/manager/password", "manager-pass-form");
		});

	}

	/**
	 * 添加或者编辑数据(弹出表单)
	 * @param title
	 * @param tempId
	 * @param size
	 * @param item 表单初始化的数据
	 * @param url 表单提交的url地址
	 * @param form_id 表单id
	 */
	exports.post = function(title, tempId, size, item, url, form_id) {

		var html = template(tempId, {item:item});
		var options = {
			title : title,
			content : html,
			icon : 'none',
			width : size.width,
			height : size.height,
			container : '#right-section',
			button : {
				'保存' : function() {
					var formId = form_id || 'content-add-form';
					if ( !exports.formCheckHandler(formId, false) ) return false;

					//collect form data
					var formData = $('#' + formId).serialize();
					popWin.lock();
					$.post(url, formData, function (data) {

						if ( data.code == '000' ) { //操作成功刷新页面
							popWin.close();
							exports.message({
								type: __global.jdialog.messageType[data.code],
								top : __global.jdialog.top,
								content:data.message
							});
							setTimeout(function() {location.reload();}, __global.reloadDelayTime);
						} else {
							popWin.unlock();
							exports.message({
								type: __global.jdialog.messageType[data.code],
								container:'.jdialog_win_box',
								content:data.message
							});
						}

					}, 'json');

				},
				'取消' : function() {
					popWin.close();
				}
			}
		}
		var options = $.extend(__global.jdialog, options);
		var popWin = JDialog.win.work(options);

		exports.initElements();
		exports.bswitchAddInit();
	}

	//搜索初始化
	exports.searchInit = function(configs) {

		if ( !configs.formId ) configs.formId = 'search-form';

		$('.search-options').on('change', function() {

			$(this).parents('.input-group-btn').next().attr('name', $(this).val());
			//获取当前选中option
			var option = $(this).find("option:selected");
			var hidden = $(option).data("hidden"); //需要隐藏的搜索项
			var show = $(option).data("show"); //需要显示的搜索项
			if ( hidden ) {
				hidden = hidden.split(",");
				$.each(hidden, function(idx, item) {
					$(item).hide();
					$(item).find('input[type="text"]').val('');
				});
			}
			if ( show ) {
				show = show.split(",");
				$.each(show, function(idx, item) {
					$(item).show();
				});
			}
		});
		$('.search-options').trigger('change'); //初始化选项框
	}

	//提示信息
	exports.message = function(options) {
		if ( !options.container ) options.container = '#right-section';
		if ( !options.timer ) options.timer = __global.jdialog.timer;

		JDialog.tip.work(options);
	}

});
